<script setup>
import { ref } from 'vue'
import { userChangePasswordService } from '@/api/user.js'
import { useUserStore } from '@/stores'
import { useRouter } from 'vue-router'

const userStore = useUserStore()
const router = useRouter()
const pwdForm = ref({
  old_pwd: '',
  new_pwd: '',
  re_pwd: ''
})
const formRef = ref()

const rules = {
  old_pwd: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^\S{6,10}$/,
      message: '密码是6-10位的非空字符',
      trigger: 'blur'
    }
  ],
  new_pwd: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^\S{6,10}$/,
      message: '密码是6-10位的非空字符',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (value === pwdForm.value.old_pwd) {
          callback(new Error('新密码不能与旧密码一致'))
        } else {
          callback()
          // console.log(value)
        }
      },
      trigger: 'blur'
    }
  ],
  re_pwd: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^\S{6,10}$/,
      message: '密码是6-10位的非空字符',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (value === pwdForm.value.new_pwd) {
          callback()
        } else {
          callback(new Error('请输入相同的密码'))
          // console.log(value)
        }
      },
      trigger: 'blur'
    }
  ]
}

const onChange = async () => {
  await formRef.value.validate()
  console.log(pwdForm.value)
  await userChangePasswordService(pwdForm.value)
  ElMessage.success('修改成功！')

  userStore.setToken('')
  userStore.setUser({})
  router.push('/login')
}
const onReset = () => {
  formRef.value.resetFields()
}
</script>
<template>
  <PageContainer title="重置密码">
    <el-form :model="pwdForm" ref="formRef" :rules="rules">
      <el-form-item
        prop="old_pwd"
        label="原密码"
        label-width="100px"
        style="width: 300px"
      >
        <el-input
          v-model="pwdForm.old_pwd"
          type="password"
          show-password
        ></el-input>
      </el-form-item>
      <el-form-item
        prop="new_pwd"
        label="新密码"
        label-width="100px"
        style="width: 300px"
      >
        <el-input
          v-model="pwdForm.new_pwd"
          type="password"
          show-password
        ></el-input>
      </el-form-item>
      <el-form-item
        prop="re_pwd"
        label="确认新密码"
        label-width="100px"
        style="width: 300px"
      >
        <el-input
          v-model="pwdForm.re_pwd"
          type="password"
          show-password
        ></el-input>
      </el-form-item>
      <el-form-item label-width="100px">
        <el-button @click="onChange" type="primary">修改密码</el-button>
        <el-button @click="onReset">重置</el-button>
      </el-form-item>
    </el-form>
  </PageContainer>
</template>
